<?php
require_once '../include/config.php';
require_once '../include/utils.class.php';
require_once '../include/orm.class.php';
require_once '../3rd_party/phpMailer/class.phpmailer.php';

$orm = new ORM();
$profile = $orm->get('pb_ht_admin', NULL, NULL, NULL, NULL, NULL)->d[0];

$opts = new stdClass();
$opts->cd = 't.sent = :v1';
$opts->cdv = array(':v1' => '0000-00-00 00:00:00');
$rslt = $orm->get('pb_ht_newsletter', 't.id', 'ASC', NULL, NULL, $opts)->d;

foreach ($rslt as $itm) {
  __send($itm);
}


function __send($obj) {
  global $orm, $profile;
  
  $obj->search = json_decode($obj->search);
  
  $opts = new stdClass();
  $opts->cd = 't.status = :v1';
  $opts->cdv = array(':v1' => 1);
  foreach ($obj->search as $key => $val) {
    __set_opts($opts, $key, $val);
  }
  $opts->sel = 't.account AS account';
  
  $rslt = $orm->get('pb_ht_customer', 't.id', 'ASC', NULL, NULL, $opts)->d;
  foreach ($rslt as $itm) {
//    for ($i = 0; $i < 500; $i++) {
      try {
        $mailer = new PHPMailer();
        $mailer->IsSMTP();
        $mailer->Host = SMTP_HOST;
        $mailer->CharSet = "UTF-8";
        
        $mailer->SMTPAuth = true;
        $mailer->Username = SMTP_USER_ATDN;
        $mailer->Password = SMTP_PASS_ATDN;
        $mailer->From = $profile->email;
        $mailer->FromName = $profile->shop_name;
        
        $mailer->Body = $obj->content;
        $mailer->Subject = $obj->subject;
      
        $mailer->isHTML(true);
        $mailer->AddAddress($itm->account, '');
        $mailer->Send();
      } catch (phpmailerException $e) {
        echo $e->errorMessage(); //Pretty error messages from PHPMailer
      } catch (Exception $e) {
        echo $e->getMessage(); //Boring error messages from anything else!
      }
//    }
  }
  $obj->sent = date('Y-m-d H:i:s', time());
  $orm->update('pb_ht_newsletter', $obj);
}

function __set_opts($opts, $key, $val) {
  if (count($val) > 0) {
    $opts->cd .= ' AND ('; 
    foreach ($val as $idx => $itm) {
      $opts->cd .= $key . " = :$key$idx";
      if ($idx < count($val) - 1) {
        $opts->cd .= ' OR ';
      }
      $opts->cdv[":$key$idx"] = $itm;
    }
    $opts->cd .= ')'; 
  }
}
?>